package soko.control;

import java.io.FileNotFoundException;
import soko.sokoban.CharNotFoundException;
import soko.sokoban.InvalidBoardException;
import soko.sokoban.Tiles;

/**
 * This is the control and view class for the Sokoban solver.
 * It controls the commandline interface.
 */
public class TUI {

	/**
	 * The input file to a screen.
	 */
	String inputFile;

	/**
	 * Constructs a new TUI
	 * 
	 * @param inputFile the input file to a screen.
	 */
	public TUI(String inputFile) {
		this.inputFile = inputFile;
	}
	
	/**
	 * Initialises this TUI.
	 * 
	 * @param findDeadlock false for normal solve, true to find the first deadlock state
	 * @param removeDeadlocks true to remove deadlock states, false for no deadlock detection
	 * @param countAllStates true to count all possible states and solutions
	 * @param lurd null or empty to not apply a lurd string to the initial state, or a string consisting of
	 * only l u r and d characters to apply a lurd string to the initial state
	 */
	public void init(boolean findDeadlock, boolean removeDeadlocks, boolean countAllStates, String lurd) {
		
		long time = System.currentTimeMillis();
		
		System.err.println("Opening: "+inputFile);
		Parser parser = new Parser(inputFile);
		Tiles tiles;
		try {
			tiles = parser.getScreen();

			Solver solver = new Solver(tiles);
			String solution = solver.getSolution(findDeadlock, removeDeadlocks, countAllStates, lurd);
			System.err.println("Time: "+(System.currentTimeMillis() - time) + " ms");
			if (countAllStates){
				System.exit(0);
			} else if(solution == null) {
				System.out.println("No solution");
				System.exit(1);
			} else {
				System.out.println(solution);
				System.exit(0);
			}

		} catch (FileNotFoundException ex) {
			System.err.println(ex.getMessage());
			System.exit(1);
		} catch (CharNotFoundException ex) {
			System.err.println(ex.getMessage());
			System.exit(1);
		} catch (InvalidBoardException ex) {
			System.err.println(ex.getMessage());
			System.exit(1);
		}
	}
}